class ListNode {
    int val;
    ListNode next;
    ListNode() {}
    ListNode(int val) { this.val = val; }
    ListNode(int val, ListNode next) { this.val = val; this.next = next; }
}
class Solution {
    public ListNode reverseKGroup(ListNode head, int k) {
        //求一共需要翻转多少组
        ListNode cur = head;
        int count = 0;
        while(cur != null){
            count++;
            cur = cur.next;
        }
        int group = count / k;
        //分组翻转
        ListNode newHead = new ListNode();
        ListNode prev = newHead;
        cur = head;
        while(group > 0){
            int num = k;
            ListNode tail = cur;
            while(cur != null && num > 0){
                ListNode next = cur.next;
                cur.next = prev.next;
                prev.next = cur;
                cur = next;
                num--;
            }
            prev = tail;
            group--;
        }
        prev.next = cur;
        return newHead.next;
    }
}